package com.centling.smartSealForPhone.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.view.View;

import com.centling.smartSealForPhone.R;
import com.centling.smartSealForPhone.fragment.StampActivity;
import com.centling.smartSealForPhone.activity.StampDetailActivity;
import com.centling.smartSealForPhone.activity.StampTimeLimitActivity;
import com.centling.smartSealForPhone.adapter.RvStampListAdapter;
import com.centling.smartSealForPhone.bean.DeviceTypeBean;
import com.centling.smartSealForPhone.bean.StampListBean;
import com.centling.smartSealForPhone.constants.GlobalData;
import com.centling.smartSealForPhone.constants.UrlConstants;
import com.centling.smartSealForPhone.utils.OkHttpUtil;
import com.centling.smartSealForPhone.utils.ShowDialog;
import com.centling.smartSealForPhone.utils.ShowToast;
import com.centling.smartSealForPhone.widget.AutoRecyclerView;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;

/**
 * @author fionera
 */
public class StampSearchFragment
        extends TitleBarFragment {

    private AutoRecyclerView rvStamp;
    private List<StampListBean.RowsEntity> stampList = new ArrayList<>();
    private StampListBean stampListBean;
    private PtrClassicFrameLayout ptrStampList;

    private int pageIndex = 0;

    private String keyWord;

    private DeviceTypeBean deviceTypeBean;

    public static StampSearchFragment getInstance(String key) {
        StampSearchFragment fragment = new StampSearchFragment();
        Bundle bundle = new Bundle();
        bundle.putString("key", key);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public int setLayoutResource() {
        return R.layout.fragment_stamp_search_list;
    }

    @Override
    public void findViewInThisFunction(View rootView) {
        setTitleBarText("搜索结果");
        setTitleBarLeft(R.drawable.ic_action_back);
        setTitleBarLeftClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mActivity.onBackPressed();
            }
        });
        initView(rootView);
        initData();
    }

    private void initView(View view) {
        ptrStampList = view.findViewById(R.id.ptr_stamp_search_list);
        rvStamp = view.findViewById(R.id.rv_stamp_search_list);
    }

    private void initData() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            keyWord = (String) bundle.get("key");
        }

        rvStamp.setLayoutManager(new GridLayoutManager(mContext, 1));
        RvStampListAdapter adapter = new RvStampListAdapter(mContext, stampList);
        rvStamp.setAdapter(adapter);
        adapter.setOnItemClickListener(new RvStampListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int pos) {
                startActivity(
                        new Intent(getActivity(), StampDetailActivity.class).putExtra("sealApplyId",
                                stampList.get(pos).getSealApplyId()));
            }
        });
        adapter.setOnButtonClickListener(new RvStampListAdapter.OnButtonClickListener() {
            @Override
            public void onButtonClick(View view, int pos, int type) {
                switch (type) {
                    case 0:
                        sendRequestToCheckIsUse(stampList.get(pos), pos);
                        break;
                    case 1:
                        clickToStopStamp(stampList.get(pos).getSealApplyId());
                        break;
                    default:
                        break;
                }
            }
        });

        ptrStampList.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                sendRequestToGetStampSearchList(true);
            }
        });

        rvStamp.setLoadDataListener(new AutoRecyclerView.LoadDataListener() {
            @Override
            public void onLoadMore() {
                sendRequestToGetStampSearchList(false);
            }
        });

        ptrStampList.post(new Runnable() {
            @Override
            public void run() {
                ptrStampList.autoRefresh();
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        ptrStampList.post(new Runnable() {
            @Override
            public void run() {
                ptrStampList.autoRefresh();
            }
        });
    }

    private void sendRequestToGetStampSearchList(final boolean isRefresh) {
        if (isRefresh) {
            pageIndex = 0;
        }
        Map<String, String> params = new HashMap<>();
        params.put("keyWord", keyWord);
        postJsonEnqueue(String.format(Locale.CHINA, UrlConstants.STAMP_SEARCH_LIST, pageIndex),
                params, new OkHttpUtil.NetCallBack() {
                    @Override
                    public void onSucceed(String json) {
                        if (isRefresh) {
                            stampList.clear();
                            ptrStampList.post(new Runnable() {
                                @Override
                                public void run() {
                                    ptrStampList.autoRefresh();
                                }
                            });
                        }
                        stampListBean = new Gson().fromJson(json, StampListBean.class);
                        stampList.addAll(stampListBean.getRows());
                        rvStamp.getAdapter().notifyDataSetChanged();
                        if (stampListBean != null && stampListBean.getRows().size() < 20) {
                            rvStamp.loadMoreComplete(true);
                        } else {
                            rvStamp.loadMoreComplete(false);
                        }
                        ptrStampList.refreshComplete();
                        pageIndex++;
                    }

                    @Override
                    public void onFailed(String reason) {
                        ShowToast.shortTime(reason);
                        ptrStampList.refreshComplete();
                        rvStamp.loadMoreComplete(false);
                    }
                });
    }

    private void sendRequestToGetTimes(final int pos) {
        mProcessDialog.setTitle("正在获取用印信息").showNormal();
        getEnqueue(String.format(Locale.CHINA, UrlConstants.GET_STAMP_REMAIN_TIMES_NEW, stampList.get(pos).getSealApplyId()),
                new OkHttpUtil.NetCallBack() {
                    @Override
                    public void onSucceed(String json) {
                        mProcessDialog.dismiss();
                        Intent intent = new Intent(mContext, StampTimeLimitActivity.class);
                        intent.putExtra("sealApplyId", stampList.get(pos).getSealApplyId());
                        intent.putExtra("macAddress", stampList.get(pos).getSealEquipBlueToothMac());
                        intent.putExtra("equipSn", stampList.get(pos).getEmbenedSn());
                        intent.putExtra("sealApplyStartTime", stampList.get(pos).getApplyStartTimeReal());
                        intent.putExtra("sealApplyEndTime", stampList.get(pos).getApplyEndTimeReal());
                        mContext.startActivity(intent);
                    }

                    @Override
                    public void onFailed(String reason) {
                        mProcessDialog.dismiss();
                        ShowToast.shortTime(reason);
                    }
                });
    }

    private void sendRequestToCheckIsUse(final StampListBean.RowsEntity rowsBean, final int pos) {
        getEnqueue(String.format(Locale.CHINA, UrlConstants.GET_DEVICE_STATE_NEW + "?embenedSn=%s",
                GlobalData.USESEAL, rowsBean.getEmbenedSn()), new OkHttpUtil.NetCallBack() {
            @Override
            public void onSucceed(String json) {
                deviceTypeBean = new Gson().fromJson(json, DeviceTypeBean.class);
                if (deviceTypeBean.isAllowed()) {
                    clickToStamp(pos);
                } else {
                    ShowToast.shortTime(deviceTypeBean.getMessage());
                }
            }

            @Override
            public void onFailed(String reason) {
                ShowToast.shortTime(reason);
            }
        });
    }

    private void clickToStamp(int pos) {
        if (TextUtils.equals(stampList.get(pos).getApplyType(), "COUNT_LIMIT")) {
            Intent intent = new Intent(mContext, StampActivity.class);
            intent.putExtra("sealApplyId", stampList.get(pos).getSealApplyId());
            intent.putExtra("macAddress", stampList.get(pos).getSealEquipBlueToothMac());
            intent.putExtra("equipSn", stampList.get(pos).getEmbenedSn());
            mContext.startActivity(intent);
        } else {
            sendRequestToGetTimes(pos);
        }
    }

    private void clickToStopStamp(final String sealApplyId){
        ShowDialog.showSelectDialog(mContext, "警告", "确定将结束用印，剩余次数无法使用", "", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, String> param = new HashMap<>();
                param.put("sealApplyId", sealApplyId);
                postJsonEnqueue(UrlConstants.STOP_STAMP, param, new OkHttpUtil.NetCallBack() {
                    @Override
                    public void onSucceed(String json) {
                        sendRequestToGetStampSearchList(true);
                    }

                    @Override
                    public void onFailed(String reason) {
                        ShowToast.shortTime("提前结束用印失败，请重试");
                    }
                });
            }
        });
    }
}
